package one.stand.controller.index;

import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.base.TemplateApi;
import com.jmp.base.dto.*;
import com.jmp.feign.BannerFeign;
import com.jmp.feign.GoodsFeign;
import com.jmp.feign.TemplateFeign;
import com.jmp.service.api.admin.BannerApi;
import com.jmp.service.api.admin.dto.BannerListDto;
import com.jmp.service.api.admin.dto.BannerListVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.Builder;
import lombok.Data;
import one.stand.advice.ResultEnum;
import one.stand.dto.ConvertUtils;
import one.stand.dto.PageRequest;
import one.stand.dto.PageResponse2;
import one.stand.mapper.GoodSpecMapperExt;
import one.stand.model.GoodSpecModel;
import one.stand.model.Goods;
import one.stand.model.ResultModel;
import one.stand.service.GoodsBaseService;
import one.stand.service.GoodsPhotoService;
import one.stand.service.OrderInfoBaseService;
import one.stand.util.AssertUtil;
import one.stand.util.MoneyUtil;
import one.stand.util.OneStringUtils;
import one.stand.util.RequestContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Api(description = "拼团")
@RequestMapping("goods/group")
@RestController
public class GoodsGroupController {
    @Autowired
    private BannerFeign bannerFeign;
    @Autowired
    private GoodsFeign goodsFeign;
    @Autowired
    private TemplateFeign templateFeign;

    @Autowired
    private GoodsBaseService goodsBaseService;
    @Autowired
    private GoodsPhotoService goodsPhotoService;
    @Autowired
    private GoodSpecMapperExt goodSpecMapperExt;
    @Autowired
    private OrderInfoBaseService orderInfoBaseService;

    @ApiOperation(value = "1:列表")
    @GetMapping("list")
    public ResultModel<GoodsGroupListResponse> list(@RequestAttribute PageRequest request) {

        //banner list
        List<GoodsGroupListResponse.Banner> iconList = null;
        if (request.getPageNum() == 1) {
            ResultModel<BannerListVo> bannerListVoResultModel = getBanners();
            iconList = ConvertUtils.list(bannerListVoResultModel.getData().getBannerPage().getList(), companyBanner -> GoodsGroupListResponse.Banner.builder()
                    .bannerId(companyBanner.getId())
                    .source(companyBanner.getSource())
                    .event(companyBanner.getEvent())
                    .eventId(companyBanner.getEventId())
                    .memo(companyBanner.getMemo())
                    .sizeRate(companyBanner.getSizeRate())
                    .build());
        }

        GoodsGroupListDto goodsGroupListDto = GoodsGroupListDto.builder()
                .companyId(RequestContextHolder.getRequestContext().isLogin() ? RequestContextHolder.getRequestContext().getUser().getCompanyId() : null)
                .build();
        goodsGroupListDto.setPageInit(request.getPageNum(), request.getPageSize());
        ResultModel<GoodsGroupListVo> resultModel = goodsFeign.groupList(goodsGroupListDto);
        AssertUtil.isTrue(resultModel);
        PageResponse2<GoodsGroupListResponse.Group> page = ConvertUtils.page2(resultModel.getData().getPage(), group -> {
            Goods goods = goodsBaseService.get(group.getGoodsId());
            return GoodsGroupListResponse.Group.builder()
                    .groupId(group.getId())
                    .photo(OneStringUtils.photoResize8(group.getPhoto()))
                    .title(group.getTitle())
                    .removePrice(Objects.nonNull(goods) ? goods.getRetailPrice() : null)
                    .groupBuyingPrice(Objects.nonNull(goods) ? goods.getPrice() : null)
                    .time(group.getEndTime().getTime())
                    .num(orderInfoBaseService.countGroup(group.getId()))
                    .build();
        });

        GoodsGroupListResponse response = GoodsGroupListResponse.builder()
                .bannerList(iconList)
                .groupPage(page)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "2:详情")
    @GetMapping("info")
    @SecurityAuthCheck
    public ResultModel<GoodsGroupInfoResponse> info(@RequestAttribute GoodsGroupInfoRequest request) {
        AssertUtil.nonNull(request.getGroupId(), ResultEnum.PARAM_CHECK);

        ResultModel<GoodsGroupInfoVo> resultModel = goodsFeign.groupInfo(GoodsGroupInfoDto.builder()
                .id(request.getGroupId())
                .build());
        AssertUtil.isTrue(resultModel);
        GoodsGroupInfoVo group = resultModel.getData();
        AssertUtil.isTrue(Objects.nonNull(group) && group.getStatus() == 1, ResultEnum.PARAM_CHECK, "活动已下架");
//        Date now = new Date();
//        Long time = group.getEndTime().getTime() - now.getTime();
//        AssertUtil.isTrue(time > 0, ResultEnum.PARAM_CHECK, "活动结束");
        Goods goods = goodsBaseService.get(group.getGoodsId());
        AssertUtil.isTrue(Objects.nonNull(goods) && goods.getIsDel() == 0, ResultEnum.PARAM_CHECK, "商品已下架");

        //商品规格
        GoodSpecModel specModel = new GoodSpecModel();
        specModel.setGoodsId(goods.getGoodsId());
        specModel.setIsDel(0);
        List<GoodSpecModel> specModelList = goodSpecMapperExt.getSpec(specModel);
        List<GoodsGroupInfoResponse.Spec> goodSpecModelList = ConvertUtils.list(specModelList, goodSpecModel -> GoodsGroupInfoResponse.Spec.builder()
                .specId(goodSpecModel.getSpecId())
                .specName(goodSpecModel.getSpecName())
                .goodSpecModelList(ConvertUtils.list(goodSpecModel.getGoodSpecModelList(), spec -> GoodsGroupInfoResponse.Spec.builder()
                        .specId(spec.getSpecId())
                        .specName(StringUtils.isNoneBlank(spec.getSpecAttribute()) ? spec.getSpecAttribute() : spec.getSpecName())
                        .specNum(spec.getSpecNum())
                        .price(MoneyUtil.getMoney(spec.getPrice()))
                        .build()))
                .build());

        //banner list
        ResultModel<BannerListVo> bannerListVoResultModel = getBanners();
        List<GoodsGroupInfoResponse.Banner> iconList = ConvertUtils.list(bannerListVoResultModel.getData().getBannerPage().getList(), companyBanner -> GoodsGroupInfoResponse.Banner.builder()
                .bannerId(companyBanner.getId())
                .source(companyBanner.getSource())
                .event(companyBanner.getEvent())
                .eventId(companyBanner.getEventId())
                .memo(companyBanner.getMemo())
                .sizeRate(companyBanner.getSizeRate())
                .build());

        GoodsGroupInfoResponse response = GoodsGroupInfoResponse.builder()
                .groupId(group.getId())
                .startTime(group.getStartTime().getTime())
                .time(group.getEndTime().getTime())
                .hidePhotos(group.getHidePhotos())
                .videoUrl(group.getVideoUrl())
                .retailPrice(goods.getRetailPrice())
                .wholesalePrice(goods.getWholesalePrice())
                .groupBuyingPrice(goods.getPrice())

                .goodsId(goods.getGoodsId())
                .goodsName(goods.getGoodsName())
                .goodsPhotos(goodsPhotoService.getListPath(goods.getGoodsId()))
                .goodsVideo(goods.getVideoUrl())
                .goodsDetails(goods.getGoodsDetails())
                .goodSpecModelList(goodSpecModelList)

                .bannerList(iconList)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "3分享")
    @GetMapping("/share")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<GoodsGroupShareResponse> share(@RequestAttribute GoodsGroupShareRequest request) {
        AssertUtil.nonNull(request.getGroupId(), ResultEnum.PARAM_CHECK);

        ResultModel<GoodsGroupInfoVo> resultModel = goodsFeign.groupInfo(GoodsGroupInfoDto.builder()
                .id(request.getGroupId())
                .build());
        AssertUtil.isTrue(resultModel);
        GoodsGroupInfoVo group = resultModel.getData();
        AssertUtil.isTrue(Objects.nonNull(group) && group.getStatus() == 1, ResultEnum.PARAM_CHECK, "活动已下架");
        Date now = new Date();
        AssertUtil.isTrue(group.getEndTime().getTime() - now.getTime() > 0, ResultEnum.PARAM_CHECK, "活动已结束");
        Goods goods = goodsBaseService.get(group.getGoodsId());
        AssertUtil.isTrue(Objects.nonNull(goods) && goods.getIsDel() == 0, ResultEnum.PARAM_CHECK, "商品已下架");
        BigDecimal price = Objects.nonNull(request.getPrice()) ? request.getPrice() : goods.getRetailPrice();
        Integer cardId = RequestContextHolder.getRequestContext().getUser().getCardId();
        String shareH5Url = goodsBaseService.getGroupShareH5Url(cardId, request.getGroupId(), String.valueOf(price));

        TemplateGet2Request getRequest = TemplateGet2Request.builder()
                .templateType(TemplateApi.Type.ID_GROUP)
                .cardId(cardId)
                .groupId(request.getGroupId())
                .groupPrice(String.valueOf(price))
                .groupH5Url(shareH5Url)
                .build();
        ResultModel<TemplateGetResponse> getResponseResultModel = templateFeign.get2(getRequest);
        AssertUtil.isTrue(getResponseResultModel);
        String cardUrl = getResponseResultModel.getData().getImageUrl();

        GoodsGroupShareResponse response = GoodsGroupShareResponse.builder()
                .shareTitle(group.getTitle())
                .shareSubTitle(group.getTitle())
                .shareImg(OneStringUtils.photoResizeShareH5(group.getPhoto()))
                .shareUrl(shareH5Url)
                .cardUrl(cardUrl)
                .build();
        return ResultModel.success(response);
    }

    private ResultModel<BannerListVo> getBanners() {
        BannerListDto bannerListDto = BannerListDto.builder()
                .companyId(BannerApi.COMPANY_ID_PLATFORM)
                .bannerType(BannerApi.BANNER_TYPE_GROUP_BUYING)
                .refId(null)
                .build();
        bannerListDto.setAll();
        ResultModel<BannerListVo> bannerListVoResultModel = bannerFeign.list(bannerListDto);
        AssertUtil.isTrue(bannerListVoResultModel);
        return bannerListVoResultModel;
    }

    @Data
    @Builder
    public static class GoodsGroupListResponse {
        @ApiModelProperty(value = "拼团活动列表(分页)", dataType = "GoodsGroupListResponse.Group")
        private PageResponse2<Group> groupPage;
        @ApiModelProperty(value = "BANNER,只有第一页有数据", dataType = "GoodsGroupListResponse.Banner")
        private List<Banner> bannerList;

        @Data
        @Builder
        @ApiModel("GoodsGroupListResponse.Banner")
        public static class Banner {
            @ApiModelProperty("ID")
            private Integer bannerId;
            @ApiModelProperty("图片地址")
            private String source;
            @ApiModelProperty("点击事件：0 无 1 商品详情 2h5 3企业 4商品列表 5专题页 6奖券系统")
            private Integer event;
            @ApiModelProperty("点击事件参数")
            private String eventId;
            @ApiModelProperty("描述")
            private String memo;
            @ApiModelProperty("宽高比: 宽/高")
            private BigDecimal sizeRate;
        }

        @Data
        @Builder
        @ApiModel("GoodsGroupListResponse.Group")
        public static class Group {
            @ApiModelProperty("ID")
            private Integer groupId;
            @ApiModelProperty("图片")
            private String photo;
            @ApiModelProperty("标题")
            private String title;
            @ApiModelProperty("零售价(划掉的那个)")
            private BigDecimal removePrice;
            @ApiModelProperty("拼团价")
            private BigDecimal groupBuyingPrice;
            @ApiModelProperty("结束时间(时间戳|毫秒)")
            private Long time;
            @ApiModelProperty("多少人已团")
            private Integer num;
        }
    }

    @Data
    public static class GoodsGroupInfoRequest {
        private Integer groupId;
    }

    @Data
    @Builder
    public static class GoodsGroupInfoResponse {
        @ApiModelProperty("ID（第几期）")
        private Integer groupId;
        @ApiModelProperty("开始时间(时间戳|毫秒)")
        private Long startTime;
        @ApiModelProperty("结束时间(时间戳|毫秒)")
        private Long time;
        @ApiModelProperty("APP专属内容,图片")
        private String hidePhotos;
        @ApiModelProperty("视频介绍")
        private String videoUrl;
        @ApiModelProperty("零售价")
        private BigDecimal retailPrice;
        @ApiModelProperty("批发价")
        private BigDecimal wholesalePrice;
        @ApiModelProperty("拼团价")
        private BigDecimal groupBuyingPrice;

        @ApiModelProperty("商品ID")
        private Integer goodsId;
        @ApiModelProperty("商品视频")
        private String goodsVideo;
        @ApiModelProperty("商品图片,多张逗号分割")
        private List<String> goodsPhotos;
        @ApiModelProperty("商品名称")
        private String goodsName;
        @ApiModelProperty("商品详情")
        private String goodsDetails;
        @ApiModelProperty(value = "规格", dataType = "GoodsGroupInfoResponse.Spec")
        private List<Spec> goodSpecModelList;
        @ApiModelProperty(value = "BANNER", dataType = "GoodsGroupInfoResponse.Banner")
        private List<Banner> bannerList;

        @Data
        @Builder
        @ApiModel("GoodsGroupInfoResponse.Banner")
        public static class Banner {
            @ApiModelProperty("ID")
            private Integer bannerId;
            @ApiModelProperty("图片地址")
            private String source;
            @ApiModelProperty("点击事件：0 无 1 商品详情 2h5 3企业 4商品列表 5专题页 6奖券系统")
            private Integer event;
            @ApiModelProperty("点击事件参数")
            private String eventId;
            @ApiModelProperty("描述")
            private String memo;
            @ApiModelProperty("宽高比: 宽/高")
            private BigDecimal sizeRate;
        }

        @ApiModel("GoodsGroupInfoResponse.Spec")
        @Data
        @Builder
        public static class Spec {
            private Integer specId;
            private String specName;
            private Integer specNum;
            private BigDecimal price;
            @ApiModelProperty(value = "规格", dataType = "GoodsGroupInfoResponse.Spec")
            private List<Spec> goodSpecModelList;
        }
    }

    @Data
    public static class GoodsGroupShareRequest {
        @ApiModelProperty("ID")
        private Integer groupId;
        @ApiModelProperty("用户自定义零售价")
        private BigDecimal price;
    }

    @Data
    @Builder
    public static class GoodsGroupShareResponse {
        @ApiModelProperty("h5分享-标题")
        private String shareTitle;
        @ApiModelProperty("h5分享-描述")
        private String shareSubTitle;
        @ApiModelProperty("h5分享-地址")
        private String shareUrl;
        @ApiModelProperty("h5分享-图片")
        private String shareImg;
        @ApiModelProperty("海报地址")
        private String cardUrl;
    }
}
